package com.cjq.controller;

import com.cjq.bean.Message;
import com.cjq.mvc.ResponseBody;
import com.cjq.service.AdminService;
import com.cjq.service.Impl.AdminServiceImpl;
import com.cjq.util.JSONUtil;
import com.cjq.util.UserUtil;
import com.google.gson.annotations.JsonAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;


public class AdminController {
    AdminServiceImpl adminService = new AdminServiceImpl();

    @ResponseBody("/admin/login.do")
    public String login(HttpServletRequest req, HttpServletResponse resp){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2、    调用Service传参数，获得结果   判断账号密码是否正确
        System.out.println(username);

        boolean result = adminService.login(username, password);
        System.out.println(result);
        //3、    根据结果，准备不同给的返回数据
        Message msg = null;
        if (result){
            msg = new Message(0,"登录成功");       //将msg转换为json：  {status:0,result:"登录成功"}
            Calendar cl = Calendar.getInstance();
            Date date = new Date();
            String ip = req.getRemoteAddr();
            adminService.updateLoginTimeAndIP(username,date,ip);    //根据名称更新上次登录的时间和地址
            String loginphone = adminService.sessionPhoneCourier(username, password);//获取登录人的电话，只获取快递员的，管理员的不获取
            req.getSession().setAttribute("loginPhone",loginphone);
            req.getSession().setAttribute("adminUserName",username);

        }else {
            msg = new Message(-1,"登录失败");
        }

        //4、    将数据转换为JSON
        String json = JSONUtil.toJSON(msg);
        //5、    将JSON回复给ajax
        return json;

    }

//删除session，返回登录页面
    @ResponseBody("/admin/clear.do")
    public String clear(HttpServletRequest req, HttpServletResponse resp){
        req.getSession().invalidate();
        Message msg = new Message();
        msg.setStatus(0);
        msg.setResult("退出成功");
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/admin/selectloginname.do")
    public String selectloginname(HttpServletRequest req, HttpServletResponse resp){
        String userName = UserUtil.getUserName(req.getSession());
        Message msg = new Message();
        msg.setResult(userName);
        if (userName.startsWith("admi")){
            msg.setStatus(0);
        }else {
            msg.setStatus(-1);
        }
        return JSONUtil.toJSON(msg);
    }


}
